package thread;

import com.ms.common.utils.ThreadUtils;

/**
 * 使用标记变量让线程中止
 *
 * @author ganbo
 * @date 2022/10/18 13:29
 */
public class ThreadStop {


    public static void main(String[] args) throws InterruptedException {
        MyThread t = new MyThread();
        System.out.println("starting thread...");
        t.start();

        ThreadUtils.sleepSeconds(3);
        System.out.println("Interrupt thread...: " + t.getName());
        t.stop = true; // 设置共享变量为true
        t.interrupt(); // 阻塞时退出阻塞状态
        Thread.sleep(4000); // 主线程休眠3秒以便观察线程m1的中断情况
        System.out.println("Stopping application...");
    }

}


class MyThread extends Thread {

    volatile boolean stop = false;

    @Override
    public void run() {

        while (!stop) {
            System.out.println(Thread.currentThread().getName() + " is running");
            try {

            } catch (Exception e) {
                System.out.println("week up from blok...");
                stop = true;
            }
        }
        System.out.println(Thread.currentThread().getName() + " is exiting...");
    }
}